#include "widget.h"
#include "./ui_widget.h"
#include <QIcon>
#include <QFileDialog>
#include <QDir>
#include <QMessageBox>
#include <QRegularExpression>
#include <QThreadPool>
#include <QThread>
#include <QRunnable>
#include <QProcess>

#include <QTimer>

#include "mergewidget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    // 在构造函数或合适的位置添加
    this->setWindowIcon(QIcon(":/logo.ico"));

    connect(ui->outputOptionsEdit, &QTextEdit::textChanged,
            this, &Widget::on_outputOptionsEdit_textChanged);

    initOptionHelp();

    // 连接选项帮助按钮
    connect(ui->optionsHelpButton, &QPushButton::clicked, this, &Widget::showOptionHelp);

    flashTimer = new QTimer(this);
    flashCount = 0;
    connect(flashTimer, &QTimer::timeout, this, &Widget::resetInputStyle);

    // In Widget constructor:
    //QWidget *mergeWidget = new MergeWidget(this);
    //ui->mainTabWidget->insertTab(1, mergeWidget, "合并");

    // 合并页面的信号连接
    connect(ui->addFileButton, &QPushButton::clicked, this, [this]() {
        MergeWidget::onAddFile(this);
    });
    connect(ui->removeFileButton, &QPushButton::clicked, this, [this]() {
        MergeWidget::onRemoveFile(this);
    });
    connect(ui->moveUpButton, &QPushButton::clicked, this, [this]() {
        MergeWidget::onMoveUp(this);
    });
    connect(ui->moveDownButton, &QPushButton::clicked, this, [this]() {
        MergeWidget::onMoveDown(this);
    });
    connect(ui->outputPathButton, &QPushButton::clicked, this, [this]() {
        MergeWidget::onOutputPathSelect(this);
    });
    connect(ui->mergeRunButton, &QPushButton::clicked, this, [this]() {
        MergeWidget::onRunMerge(this);
    });

}

Widget::~Widget()
{
    delete ui;
}

QString Widget::buildFFmpegCommand(const QString &ffmpegPath, const QString &inputFile,
                                 const QString &options, const QString &outputFile) {
    return QString("%1 -y -hide_banner -i \"%2\" %3 \"%4\"")
            .arg(ffmpegPath)
            .arg(inputFile)
            .arg(options)
            .arg(outputFile);
}

void Widget::on_inputDirButton_clicked()
{
    QString dir = QFileDialog::getExistingDirectory(
        this,
        tr("选择输入目录"),
        QDir::homePath(),
        QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks
    );

    if(!dir.isEmpty()) {
        ui->inputDirEdit->setText(dir);
        ui->inputDirRadio->setChecked(true);
    }
}

void Widget::on_inputFileButton_clicked()
{
    QString file = QFileDialog::getOpenFileName(
        this,
        tr("选择输入文件"),
        QDir::homePath(),
        tr("所有文件 (*.*)")
    );

    if(!file.isEmpty()) {
        ui->inputFileEdit->setText(file);
        ui->inputFileRadio->setChecked(true);
    }
}

void Widget::on_outputDirButton_clicked()
{
    QString dir = QFileDialog::getExistingDirectory(
        this,
        tr("选择输出目录"),
        QDir::homePath(),
        QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks
    );

    if(!dir.isEmpty()) {
        ui->outputDirEdit->setText(dir);
    }
}

class FFmpegWorkerOne : public QRunnable {
public:
    FFmpegWorkerOne(const QString &cmd, QObject *uiLog, QObject *button)
        : cmd(cmd), uiLog(uiLog), button(button) {}

    void run() override {
        QMetaObject::invokeMethod(uiLog, "append",
                                        Qt::QueuedConnection,
                                        Q_ARG(QString, "<font color='blue'>转换命令：</font>"));
        QMetaObject::invokeMethod(uiLog, "append",
                                        Qt::QueuedConnection,
                                        Q_ARG(QString, "<font color='blue'>" + cmd + "</font>"));

        QProcess process;
        process.setProcessChannelMode(QProcess::MergedChannels);
        process.start(cmd);

        while (process.state() != QProcess::NotRunning) {
            process.waitForReadyRead();
            QByteArray output = process.readAll();
            if (!output.isEmpty()) {
                QMetaObject::invokeMethod(uiLog, "append",
                                        Qt::QueuedConnection,
                                        Q_ARG(QString, QString::fromUtf8(output)));
            }
        }

        // Enable button after completion
        QMetaObject::invokeMethod(uiLog, "append",
                                        Qt::QueuedConnection,
                                        Q_ARG(QString, "<font color='green'>-----转换完成！-----</font>"));
        QMetaObject::invokeMethod(button, "setEnabled",
                                Qt::QueuedConnection,
                                Q_ARG(bool, true));
    }

private:
    QString cmd;
    QObject* uiLog;
    QObject* button;
};

// 修改FFmpegWorker类中的run函数,使用getFFmpegPath
class FFmpegWorker : public QRunnable {
public:
    FFmpegWorker(const QString &inputFile, const QString &outputDir,
                 const QString &outputExt, const QString &options,
                 QObject *ui, QObject *uiLog, const QString &ffmpegPath, Widget *widget, QObject *button, int *counter, int total)
        : inputFile(inputFile), outputDir(outputDir), outputExt(outputExt),
    options(options), ui(ui), uiLog(uiLog), ffmpegPath(ffmpegPath), widget(widget), button(button), completedTasks(counter), totalTasks(total) {}

    void run() override {
        QMetaObject::invokeMethod(uiLog, "append",
                                        Qt::QueuedConnection,
                                        Q_ARG(QString, inputFile));

        QFileInfo fi(inputFile);
        QString outputFile = QDir(outputDir).filePath(fi.baseName() + "." + outputExt);

        QStringList args;
        args << "-i" << "\"" + inputFile + "\"";

        if (!options.isEmpty()) {
            args.append(options.split(" ", Qt::SkipEmptyParts));
        }

        args << "\"" + outputFile + "\"";

        QString cmd = widget->buildFFmpegCommand(ffmpegPath, inputFile, options, outputFile);

        QMetaObject::invokeMethod(uiLog, "append",
                                        Qt::QueuedConnection,
                                        Q_ARG(QString, "<font color='blue'>转换命令：</font>"));
        QMetaObject::invokeMethod(uiLog, "append",
                                        Qt::QueuedConnection,
                                        Q_ARG(QString, "<font color='blue'>" + cmd + "</font>"));

        QProcess process;
        process.setProcessChannelMode(QProcess::MergedChannels);
        process.start(cmd);

        while (process.state() != QProcess::NotRunning) {
            process.waitForReadyRead();
            QByteArray output = process.readAll();
            if (!output.isEmpty()) {
                QMetaObject::invokeMethod(uiLog, "append",
                                        Qt::QueuedConnection,
                                        Q_ARG(QString, QString::fromUtf8(output)));
            }
        }

        // Update counter and button state after completion
        (*completedTasks)++;
        if (*completedTasks == totalTasks) {
            QMetaObject::invokeMethod(uiLog, "append",
                                        Qt::QueuedConnection,
                                        Q_ARG(QString, "<font color='green'>-----转换完成！-----</font>"));
            QMetaObject::invokeMethod(button, "setEnabled",
                                    Qt::QueuedConnection,
                                    Q_ARG(bool, true));
        }
    }

private:
    QString inputFile;
    QString outputDir;
    QString outputExt;
    QString options;
    QObject *ui;
    QObject* uiLog;
    QString ffmpegPath;
    Widget *widget;
    QObject *button;
    int *completedTasks;
    int totalTasks;
};

// 在Widget类中添加一个获取ffmpeg路径的函数
QString Widget::getFFmpegPath() {
    // 检查当前目录下的ffmpeg目录
    QString localFFmpeg = QCoreApplication::applicationDirPath() + "/ffmpeg/bin/ffmpeg";
#ifdef Q_OS_WIN
    localFFmpeg += ".exe";
#endif

    if(QFile::exists(localFFmpeg)) {
        return localFFmpeg;
    }

    // 返回系统PATH中的ffmpeg
    return "ffmpeg";
}

void Widget::on_runButton_clicked()
{
    ui->runButton->setEnabled(false);  // 禁用运行按钮

    // 获取输入和输出路径
    QString inputPath;
    if (ui->inputDirRadio->isChecked()) {
        inputPath = ui->inputDirEdit->text();
    } else {
        inputPath = ui->inputFileEdit->text();
    }

    QString outputDir = ui->outputDirEdit->text();

    // 验证路径
    if (inputPath.isEmpty() || outputDir.isEmpty()) {
        QMessageBox::warning(this, "错误", "请设置输入和输出路径");
        ui->runButton->setEnabled(true);  // 启用运行按钮
        return;
    }

    // 创建输出目录
    QDir().mkpath(outputDir);

    // 创建线程池
    // 通过CPU核心数-1来控制并行任务数
    QThreadPool *threadPool = new QThreadPool(this);
    int maxThreads = QThread::idealThreadCount() - 1;  // 获取CPU核心数-1
    if (maxThreads < 1) maxThreads = 1;  // 确保至少有1个线程
    threadPool->setMaxThreadCount(maxThreads);

    if (ui->inputDirRadio->isChecked()) {
        // 批量处理模式
        // 获取文件列表
        QStringList inputFiles;
        QDir dir(inputPath);
        QString filter = ui->fileTypeCombo->currentText();
        // 提取括号中的格式
        QRegularExpression rx("\\((.*)\\)");
        QRegularExpressionMatch match = rx.match(filter);
        //ui->ffmpegLogEdit->append(match.captured(1));
        if (match.hasMatch()) {
            QString formats = match.captured(1);
            inputFiles = dir.entryList(formats.split(" "), QDir::Files);
            //ui->ffmpegLogEdit->append("需要转换的文件：");
            //ui->ffmpegLogEdit->append(inputFiles.join(","));
            // 添加完整路径
            for(int i = 0; i < inputFiles.size(); i++) {
                inputFiles[i] = dir.filePath(inputFiles[i]);
            }
        }
        if (inputFiles.isEmpty()) {
            QMessageBox::warning(this, "错误", "没有找到符合条件的输入文件");
            ui->runButton->setEnabled(true);  // 启用运行按钮
            return;
        }

        // 显示一行日志
        ui->ffmpegLogEdit->append("<font color='green'>----------开始执行批量模式----------</font>");

        // 创建计数器追踪完成的任务数
        int *completedTasks = new int(0);
        int totalTasks = inputFiles.size();

        QString ffmpegPath = getFFmpegPath();

        // 处理每个文件
        for (const QString &inputFile : inputFiles) {
            ui->ffmpegLogEdit->append("<font color='green'>开始转换文件：</font>");
            ui->ffmpegLogEdit->append("<font color='green'>" + inputFile + "</font>");
            QString outputExt = ui->outputExtCheck->isChecked() ?
                               ui->outputExtEdit->text() :
                               QFileInfo(inputFile).suffix();
            QString options = ui->outputOptionsEdit->toPlainText();

            auto worker = new FFmpegWorker(inputFile, outputDir, outputExt, options, ui->ffmpegCommandEdit, ui->ffmpegLogEdit, ffmpegPath, this, ui->runButton, completedTasks, totalTasks);
            worker->setAutoDelete(true);
            threadPool->start(worker);
        }
    } else {
        // 单文件模式
        QString cmd = ui->ffmpegCommandEdit->toPlainText();
        if(cmd.isEmpty()) {
            QMessageBox::warning(this, "错误", "请先设置FFmpeg命令");
            ui->runButton->setEnabled(true);  // 启用运行按钮
            return;
        }

        ui->ffmpegLogEdit->append("<font color='green'>----------开始执行单文件模式----------</font>");

        // 创建FFmpeg工作线程
        auto worker = new FFmpegWorkerOne(cmd, ui->ffmpegLogEdit, ui->runButton);
        worker->setAutoDelete(true);
        threadPool->start(worker);
    }

}

void Widget::on_videoOptionsList_itemClicked(QListWidgetItem *item)
{
    if ((ui->inputDirRadio->isChecked() && ui->inputDirEdit->text().isEmpty()) ||
        (ui->inputFileRadio->isChecked() && ui->inputFileEdit->text().isEmpty()) ||
        ui->outputDirEdit->text().isEmpty())
    {
        highlightEmptyInput();
        return;
    }

    ui->outputExtCheck->setChecked(false);
    ui->outputExtEdit->setText("");

    if(item->text() == "音视频质量不变") {
        ui->outputOptionsEdit->setPlainText("-c copy");
    }
    if(item->text() == "WEB视频流优化") {
        ui->outputOptionsEdit->setPlainText("-movflags faststart -acodec copy -vcodec copy");
    }
    if(item->text() == "H264压缩") {
        ui->outputOptionsEdit->setPlainText("-c:v libx264 -crf 23");
    }
    if(item->text() == "H264压缩-intel加速") {
        ui->outputOptionsEdit->setPlainText("-c:v h264_qsv -qscale 15");
    }
    if(item->text() == "H264压缩-AMD加速") {
        ui->outputOptionsEdit->setPlainText("-c:v h264_amf -qscale 15");
    }
    if(item->text() == "H264压缩-NV加速") {
        ui->outputOptionsEdit->setPlainText("-c:v h264_nvenc -qscale 15");
    }
    if(item->text() == "H265压缩") {
        ui->outputOptionsEdit->setPlainText("-c:v libx265 -crf 28");
    }
    if(item->text() == "H265压缩-intel加速") {
        ui->outputOptionsEdit->setPlainText("-c:v hevc_qsv -qscale 15");
    }
    if(item->text() == "H265压缩-AMD加速") {
        ui->outputOptionsEdit->setPlainText("-c:v hevc_amf -qscale 15");
    }
    if(item->text() == "H265压缩-NV加速") {
        ui->outputOptionsEdit->setPlainText("-c:v hevc_nvenc -qscale 15");
    }
    if(item->text() == "转码到mp3") {
        ui->outputExtCheck->setChecked(true);
        ui->outputExtEdit->setText("mp3");
        ui->outputOptionsEdit->setPlainText("-c:a libmp3lame -q:a 2");
    }
    if(item->text() == "gif(15fps,480p)") {
        ui->outputExtCheck->setChecked(true);
        ui->outputExtEdit->setText("gif");
        ui->outputOptionsEdit->setPlainText("-filter_complex \"[0:v] scale=480:-1, fps=15, split [a][b];[a] palettegen [p];[b][p] paletteuse\"");
    }
    if(item->text() == "区域模糊") {
        ui->outputOptionsEdit->setPlainText("-vf \"delogo=x=0:y=0:w=100:h=50\"");
    }
    if(item->text() == "视频两倍速") {
        ui->outputOptionsEdit->setPlainText("-filter:v setpts=0.5*PTS");
    }
    if(item->text() == "音频两倍速") {
        ui->outputOptionsEdit->setPlainText("-filter:a \"atempo=2.0\"");
    }
    if(item->text() == "视频倒放") {
        ui->outputOptionsEdit->setPlainText("-vf reverse -af areverse");
    }
    if(item->text() == "音频倒放") {
        ui->outputOptionsEdit->setPlainText("-af areverse");
    }
    if(item->text() == "设置画面比例") {
        ui->outputOptionsEdit->setPlainText("-aspect 16:9");
    }
    if(item->text() == "视频0.5倍速 + 光流法补帧到60帧") {
        ui->outputOptionsEdit->setPlainText("-filter:v \"setpts=2.0*PTS,minterpolate='fps=60:mi_mode=mci'\"");
    }
    if(item->text() == "从视频区间每秒提取n张照片") {
        ui->outputOptionsEdit->setPlainText("-vf fps=1");
    }
    if(item->text() == "截取指定数量的帧保存为图片") {
        ui->outputOptionsEdit->setPlainText("-vframes 1");
    }
    if(item->text() == "裁切视频画面") {
        ui->outputOptionsEdit->setPlainText("-vf crop=w:h:x:y");
    }
    if(item->text() == "视频旋转度数") {
        ui->outputOptionsEdit->setPlainText("-vf \"rotate=90*PI/180\"");
    }
    if(item->text() == "水平翻转画面") {
        ui->outputOptionsEdit->setPlainText("-vf hflip");
    }
    if(item->text() == "垂直翻转画面") {
        ui->outputOptionsEdit->setPlainText("-vf vflip");
    }
    if(item->text() == "设定至指定分辨率并且自动填充黑边") {
        ui->outputOptionsEdit->setPlainText("-vf \"scale=1920:1080:force_original_aspect_ratio=decrease,pad=1920:1080:(ow-iw)/2:(oh-ih)/2\"");
    }
    if(item->text() == "视频或音乐添加封面图片") {
        ui->outputOptionsEdit->setPlainText("-i cover.jpg -map 0 -map 1 -c copy -disposition:v:1 attached_pic");
    }
    if(item->text() == "声音响度标准化") {
        ui->outputOptionsEdit->setPlainText("-filter:a loudnorm");
    }
    if(item->text() == "音量大小调节") {
        ui->outputOptionsEdit->setPlainText("-filter:a volume=2.0");
    }
    if(item->text() == "静音第一个声道") {
        ui->outputOptionsEdit->setPlainText("-af \"pan=stereo|c0=c0|c1=0*c1\"");
    }
    if(item->text() == "静音所有声道") {
        ui->outputOptionsEdit->setPlainText("-an");
    }
    if(item->text() == "交换左右声道") {
        ui->outputOptionsEdit->setPlainText("-af \"pan=stereo|c0=c1|c1=c0\"");
    }

    // Then construct and display the complete command
    QString inputPath;
    if (ui->inputDirRadio->isChecked()) {
        inputPath = ui->inputDirEdit->text();
    } else {
        inputPath = ui->inputFileEdit->text();
    }

    QString outputDir = ui->outputDirEdit->text();

    if(!inputPath.isEmpty() && !outputDir.isEmpty()) {
        QFileInfo fi(inputPath);
        QString outputExt = ui->outputExtCheck->isChecked() ?
                          ui->outputExtEdit->text() :
                          fi.suffix();

        QString outputFile = QDir(outputDir).filePath(fi.baseName() + "." + outputExt);

        QString ffmpegPath = getFFmpegPath();
        QString options = ui->outputOptionsEdit->toPlainText();

        QString cmd = buildFFmpegCommand(ffmpegPath, inputPath, options, outputFile);

        ui->ffmpegCommandEdit->setPlainText(cmd);
    }
}

void Widget::on_audioOptionsList_itemClicked(QListWidgetItem *item)
{
    if ((ui->inputDirRadio->isChecked() && ui->inputDirEdit->text().isEmpty()) ||
        (ui->inputFileRadio->isChecked() && ui->inputFileEdit->text().isEmpty()) ||
        ui->outputDirEdit->text().isEmpty())
    {
        highlightEmptyInput();
        return;
    }

    ui->outputExtCheck->setChecked(false);
    ui->outputExtEdit->setText("");

    if(item->text() == "转码到mp3") {
        ui->outputExtCheck->setChecked(true);
        ui->outputExtEdit->setText("mp3");
        ui->outputOptionsEdit->setPlainText("-c:a libmp3lame -q:a 2");
    }
    if(item->text() == "音频两倍速") {
        ui->outputOptionsEdit->setPlainText("-filter:a \"atempo=2.0\"");
    }
    if(item->text() == "音频倒放") {
        ui->outputOptionsEdit->setPlainText("-af areverse");
    }
    if(item->text() == "声音响度标准化") {
        ui->outputOptionsEdit->setPlainText("-filter:a loudnorm");
    }
    if(item->text() == "音量大小调节") {
        ui->outputOptionsEdit->setPlainText("-filter:a volume=2.0");
    }
    if(item->text() == "静音第一个声道") {
        ui->outputOptionsEdit->setPlainText("-af \"pan=stereo|c0=c0|c1=0*c1\"");
    }
    if(item->text() == "静音所有声道") {
        ui->outputOptionsEdit->setPlainText("-an");
    }
    if(item->text() == "交换左右声道") {
        ui->outputOptionsEdit->setPlainText("-af \"pan=stereo|c0=c1|c1=c0\"");
    }

    // Then construct and display the complete command
    QString inputPath;
    if (ui->inputDirRadio->isChecked()) {
        inputPath = ui->inputDirEdit->text();
    } else {
        inputPath = ui->inputFileEdit->text();
    }

    QString outputDir = ui->outputDirEdit->text();

    if(!inputPath.isEmpty() && !outputDir.isEmpty()) {
        QFileInfo fi(inputPath);
        QString outputExt = ui->outputExtCheck->isChecked() ?
                          ui->outputExtEdit->text() :
                          fi.suffix();

        QString outputFile = QDir(outputDir).filePath(fi.baseName() + "." + outputExt);

        QString ffmpegPath = getFFmpegPath();
        QString options = ui->outputOptionsEdit->toPlainText();

        QString cmd = buildFFmpegCommand(ffmpegPath, inputPath, options, outputFile);

        ui->ffmpegCommandEdit->setPlainText(cmd);
    }
}

void Widget::on_imageOptionsList_itemClicked(QListWidgetItem *item)
{
    if ((ui->inputDirRadio->isChecked() && ui->inputDirEdit->text().isEmpty()) ||
        (ui->inputFileRadio->isChecked() && ui->inputFileEdit->text().isEmpty()) ||
        ui->outputDirEdit->text().isEmpty())
    {
        highlightEmptyInput();
        return;
    }

    if(item->text() == "JPEG压缩质量(1-31,越大压缩率越高)") {
        ui->outputOptionsEdit->setPlainText("-q:v 20");
    }
    if(item->text() == "PNG无损压缩(zlib 1-9)") {
        ui->outputOptionsEdit->setPlainText("-compression_level 9");
    }
    if(item->text() == "WebP压缩(质量0-100)") {
        ui->outputOptionsEdit->setPlainText("-quality 80");
    }

    // Then construct and display the complete command
    QString inputPath;
    if (ui->inputDirRadio->isChecked()) {
        inputPath = ui->inputDirEdit->text();
    } else {
        inputPath = ui->inputFileEdit->text();
    }

    QString outputDir = ui->outputDirEdit->text();

    if(!inputPath.isEmpty() && !outputDir.isEmpty()) {
        QFileInfo fi(inputPath);
        QString outputExt = ui->outputExtCheck->isChecked() ?
                          ui->outputExtEdit->text() :
                          fi.suffix();

        QString outputFile = QDir(outputDir).filePath(fi.baseName() + "." + outputExt);

        QString ffmpegPath = getFFmpegPath();
        QString options = ui->outputOptionsEdit->toPlainText();

        QString cmd = buildFFmpegCommand(ffmpegPath, inputPath, options, outputFile);

        ui->ffmpegCommandEdit->setPlainText(cmd);
    }
}

void Widget::on_outputOptionsEdit_textChanged()
{
    QString inputPath;
    if (ui->inputDirRadio->isChecked()) {
        inputPath = ui->inputDirEdit->text();
    } else {
        inputPath = ui->inputFileEdit->text();
    }

    QString outputDir = ui->outputDirEdit->text();

    if(!inputPath.isEmpty() && !outputDir.isEmpty()) {
        QFileInfo fi(inputPath);
        QString outputExt = ui->outputExtCheck->isChecked() ?
                          ui->outputExtEdit->text() :
                          fi.suffix();

        QString outputFile = QDir(outputDir).filePath(fi.baseName() + "." + outputExt);

        QString ffmpegPath = getFFmpegPath();
        QString options = ui->outputOptionsEdit->toPlainText();

        QString cmd = buildFFmpegCommand(ffmpegPath, inputPath, options, outputFile);
        ui->ffmpegCommandEdit->setPlainText(cmd);
    }
}

void Widget::on_fileTypeCombo_currentIndexChanged(int index)
{
    switch(index) {
    case 0: // 视频格式
        ui->optionsTabWidget->setCurrentIndex(0);
        break;
    case 1: // 音频格式
        ui->optionsTabWidget->setCurrentIndex(1);
        break;
    case 2: // 图片格式
        ui->optionsTabWidget->setCurrentIndex(2);
        break;
    }
}

void Widget::initOptionHelp()
{
    // 视频选项说明
    optionHelp["音视频质量不变"] = "直接复制音视频流而不重新编码,可以快速转换容器格式";
    optionHelp["WEB视频流优化"] = "使用 faststart 优化视频以适合网络传输,可实现快速播放";
    optionHelp["H264压缩"] = "使用 libx264 编码器压缩视频,crf值23为默认压缩率";
    optionHelp["H264压缩-intel加速"] = "使用Intel Quick Sync硬件加速H264编码,需要支持QSV的CPU";
    optionHelp["H264压缩-AMD加速"] = "使用AMD AMF硬件加速H264编码,需要AMD显卡支持";
    optionHelp["H264压缩-NV加速"] = "使用NVIDIA NVENC硬件加速H264编码,需要NVIDIA显卡支持";
    optionHelp["H265压缩"] = "使用 libx265 编码器压缩视频,crf值28为默认压缩率";
    optionHelp["H265压缩-intel加速"] = "使用Intel Quick Sync硬件加速H265/HEVC编码";
    optionHelp["H265压缩-AMD加速"] = "使用AMD AMF硬件加速H265/HEVC编码";
    optionHelp["H265压缩-NV加速"] = "使用NVIDIA NVENC硬件加速H265/HEVC编码";
    optionHelp["视频两倍速"] = "加快视频播放速度为2倍,保持音频不变";
    optionHelp["视频倒放"] = "视频画面倒序播放";
    optionHelp["设置画面比例"] = "设置视频的显示宽高比,如16:9、4:3等";
    optionHelp["视频0.5倍速 + 光流法补帧到60帧"] = "将视频减速至0.5倍,并使用光流法进行补帧处理";
    optionHelp["裁切视频画面"] = "裁剪视频画面指定区域,参数为:宽:高:X:Y";
    optionHelp["视频旋转度数"] = "旋转视频画面指定角度";
    optionHelp["水平翻转画面"] = "水平方向翻转视频画面";
    optionHelp["垂直翻转画面"] = "垂直方向翻转视频画面";
    optionHelp["设定至指定分辨率并且自动填充黑边"] = "将视频缩放至指定分辨率,保持比例并自动填充黑边";
    optionHelp["转码到mp3"] = "将视频中的音频提取并转换为MP3格式";
    optionHelp["音频两倍速"] = "加快音频播放速度为2倍,保持音调不变";
    optionHelp["音频倒放"] = "音频倒序播放";
    optionHelp["声音响度标准化"] = "标准化音频响度,使音量更均衡";
    optionHelp["音量大小调节"] = "调整音频音量大小,1.0为原始音量";
    optionHelp["静音第一个声道"] = "将第一个音频声道静音";
    optionHelp["静音所有声道"] = "移除所有音频轨道";
    optionHelp["交换左右声道"] = "交换立体声的左右声道";
    optionHelp["gif(15fps,480p)"] = "转换视频为GIF格式,15帧每秒,480p分辨率";
    optionHelp["从视频区间每秒提取n张照片"] = "按指定帧率从视频中提取图片";
    optionHelp["截取指定数量的帧保存为图片"] = "截取视频中指定数量的帧并保存为图片";
    optionHelp["视频或音乐添加封面图片"] = "为视频或音频文件添加封面图片";

    // 音频选项说明
    optionHelp["转码到mp3"] = "将音频转换为MP3格式,使用LAME编码器";
    optionHelp["音频两倍速"] = "加快音频播放速度为2倍,保持音调不变";
    optionHelp["音频倒放"] = "音频倒序播放";
    optionHelp["声音响度标准化"] = "使用loudnorm滤镜标准化音频响度";
    optionHelp["音量大小调节"] = "使用volume滤镜调整音频音量";
    optionHelp["静音第一个声道"] = "使用pan滤镜将第一个声道静音";
    optionHelp["静音所有声道"] = "移除所有音频数据";
    optionHelp["交换左右声道"] = "交换立体声音频的左右声道";

    // 图像选项说明
    optionHelp["JPEG压缩质量(1-31,越大压缩率越高)"] = "设置JPEG压缩质量,1-31,值越大压缩率越高质量越低";
    optionHelp["PNG无损压缩(zlib 1-9)"] = "设置PNG压缩级别,1-9,值越大压缩率越高";
    optionHelp["WebP压缩(质量0-100)"] = "设置WebP压缩质量,0-100,值越大质量越好";
    optionHelp["从视频区间每秒提取n张照片"] = "按指定频率从视频中提取图片帧";
    optionHelp["截取指定数量的帧保存为图片"] = "从视频中截取指定数量的帧并保存";
    optionHelp["视频或音乐添加封面图片"] = "为媒体文件添加封面图片";
}


void Widget::showOptionHelp()
{
    QListWidget* currentList = nullptr;

    // 获取当前选项卡对应的列表控件
    switch(ui->optionsTabWidget->currentIndex()) {
        case 0:
            currentList = ui->videoOptionsList;
        break;
        case 1:
            currentList = ui->audioOptionsList;
        break;
        case 2:
            currentList = ui->imageOptionsList;
        break;
    }

    if(!currentList) return;

    // 获取选中项或第一项
    QListWidgetItem* currentItem = currentList->currentItem();
    if(!currentItem) {
        currentItem = currentList->item(0);
    }

    QString optionText = currentItem->text();
    QString helpText = optionHelp.value(optionText, "暂无该选项的说明");

    QMessageBox::information(this, "选项说明", helpText);
}


void Widget::highlightEmptyInput()
{
    QString redBorderStyle = "border: 2px solid red;";
    flashCount = 0;

    if (ui->inputDirRadio->isChecked() && ui->inputDirEdit->text().isEmpty()) {
        ui->inputDirEdit->setStyleSheet(redBorderStyle);
    }

    if (ui->inputFileRadio->isChecked() && ui->inputFileEdit->text().isEmpty()) {
        ui->inputFileEdit->setStyleSheet(redBorderStyle);
    }

    if (ui->outputDirEdit->text().isEmpty()) {
        ui->outputDirEdit->setStyleSheet(redBorderStyle);
    }

    flashTimer->start(500); // 每500毫秒闪烁一次
}

void Widget::resetInputStyle()
{
    flashCount++;
    QString emptyStyle = "";
    QString redBorderStyle = "border: 2px solid red;";

    if (ui->inputDirRadio->isChecked() && ui->inputDirEdit->text().isEmpty()) {
        ui->inputDirEdit->setStyleSheet(flashCount % 2 == 0 ? redBorderStyle : emptyStyle);
    }

    if (ui->inputFileRadio->isChecked() && ui->inputFileEdit->text().isEmpty()) {
        ui->inputFileEdit->setStyleSheet(flashCount % 2 == 0 ? redBorderStyle : emptyStyle);
    }

    if (ui->outputDirEdit->text().isEmpty()) {
        ui->outputDirEdit->setStyleSheet(flashCount % 2 == 0 ? redBorderStyle : emptyStyle);
    }

    if (flashCount >= 6) { // 闪烁3次后停止
        flashTimer->stop();
        ui->inputDirEdit->setStyleSheet(emptyStyle);
        ui->inputFileEdit->setStyleSheet(emptyStyle);
        ui->outputDirEdit->setStyleSheet(emptyStyle);
    }
}